package cc.linker.steplink.crm.response;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * controller 正常返回结果处理
 * 包装{"code":"200","msg":"","data":object}
 *
 * @author zhaomengwei
 */
@Slf4j
@RestControllerAdvice(annotations = Controller.class)
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof String) {
            return o;
        }
//        HttpServletRequest req = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
//        HttpServletResponse res = ((ServletServerHttpResponse) serverHttpResponse).getServletResponse();
//        int majorVersion = getChromeVersion(req, res);
//        if(majorVersion<67){
//            LOGGER.info("=======低版本重新设置SameSite");
//            res.setHeader("Set-Cookie", res.getHeader("Set-Cookie") + ";SameSite=null");
//        }
        return ResponseGenerator.success(o);
    }


    public int getChromeVersion(HttpServletRequest request, HttpServletResponse response) {
        String userAgent = request.getHeader("user-agent");
        Browser browser = UserAgent.parseUserAgentString(userAgent).getBrowser();
        if(browser!=null&&browser.getName().contains("Chrome")){
            Version version = browser.getVersion(userAgent);
            if(!StringUtils.isEmpty(version.getMajorVersion())){
                try{
                    int majorVersion = Integer.parseInt(version.getMajorVersion());
                    // 如果是谷歌并且版本小于等67，则samesite设置为null
                    return majorVersion;
                }catch (Exception e ){
                    e.printStackTrace();
                }
            }
        }
        return 80;
    }
}
